<template>
  <el-container>
    <el-main>
      <div class="default-main ba-table-box">
        <TableHeader
          :buttons="['refresh', 'comSearch', 'columnDisplay']"
          :quick-search-placeholder="placeholder"
          @action="baTable.onTableHeaderAction"
        />
        <!-- 表格 -->
        <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
        <Table ref="tableRef" @action="baTable.onTableAction" />
        <!-- 问题跟踪表单 -->
        <PopupForm ref="formRef" v-if="baTable.form.operate" />
        <!-- 料号详情 -->
        <More
          ref="moreRef"
          v-if="processPull.showMoreForm"
          v-model="processPull.showMoreForm"
        />
      </div>
    </el-main>
  </el-container>
</template>
<script lang="ts" setup>
import _ from "lodash";
import { ref, provide, onMounted, markRaw, reactive } from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff, DictOperation } from "@/utils/common"; // 导入表格api方法生成器
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import type { TableRow, TableColumn } from "@/utils/baTable"; //表格列行类型
import { BoardProcessPull } from "@/api/backend/index";
import PopupForm from "./popupForm.vue";
import { useRoute, useRouter } from "vue-router";
import { useNavTabs } from "@/store/navTabs";
import { useDictionary } from "@/store/backend/tool/dictionary";
import Click from "./components/click.vue";
import type { FormInstance } from "element-plus";
import { useBoardProcessPull } from "@/store/backend/Board/processPull";
import { useDept } from "@/store/backend/SysM/dept";
import { useUser } from "@/store/backend/SysM/user";
import { useFollowProlem } from "@/store/backend/Board/followProlem";
import More from "./components/more.vue";
import { useBuddyGoods } from "@/store/backend/BomM/goods";
import GoodsSearch from "./components/searchTags/goods.vue";
import ProcessSearch from "./components/searchTags/process.vue";
import MtTypeSearch from "./components/searchTags/mtType.vue";
import TagSearch from "@/components/tagSearch/index.vue";

const placeholder = ref<string>("模糊搜索");
const tableRef = ref();
const formRef = ref();
const moreRef = ref();
const route = useRoute();
const router = useRouter();
const navTabs = useNavTabs();
const dictionary = useDictionary();
const goods = useBuddyGoods();
const dept = useDept();
const user = useUser();
const followProlem = useFollowProlem();
const processPull = useBoardProcessPull();

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + BoardProcessPull)
      ? (navTabs as any).pageSizeMap.get(route.path + BoardProcessPull)
      : 10;
  }
  return 50;
};

//初始化字典处理类
const dictOperation = new DictOperation();

//获取字典
const getDictionary = () => {
  //获取问题域的字典
  dictOperation.getDictionary(
    processPull,
    "sys_problem_area",
    "proCate",
    "type"
  );
  //获取晨会问题状态的字典
  dictOperation.getDictionary(
    processPull,
    "sys_problem_status",
    "proStatus",
    "statusType"
  );
};
getDictionary();

const state: {
  showMoreForm: boolean;
} = reactive({ showMoreForm: false });

const scoreOrderBySelf = (tableData: any[]) => {
  let list: any[] = [];
  tableData.forEach((_item: any) => {
    list.push(_item);
  });
  list.sort((a: any, b: any) => {
    if (a.goodReqDate === b.goodReqDate && a.goodsNo === b.goodsNo) {
      return a.seqNo - b.seqNo;
    }
    return 0;
  });
  baTable.table.data = list;
  console.log("list", list);
};

//全局事件总线
const { proxy } = useCurrentInstance();
const baTable = new baTableClass(
  new baTableApi(BoardProcessPull), //this.api = api菜单管理相关
  {
    pk: "id",
    column: [
      { type: "selection", align: "center", operator: false },
      {
        show: filedShowOff("goodsNo"),
        label: "料号",
        prop: "goodsNo",
        align: "center",
        fixed: "left",
        width: 130,
        operatorPlaceholder: "精确搜索",
        render: "customRender",
        customRender: markRaw(Click),
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(GoodsSearch),
      },
      {
        show: filedShowOff("goodReqDate"),
        label: "最近欠量时间",
        prop: "goodReqDate",
        align: "center",
        fixed: "left",
        width: 135,
        sortable: "custom",
        operator: false,
      },
      {
        show: filedShowOff("cRequests"),
        label: "最近成品欠量",
        prop: "cRequests",
        align: "center",
        fixed: "left",
        operator: false,
        width: 120,
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          if (value == "-") {
            return "<p>" + value + "</p>";
          }
          return "<p>" + (value - 0).toFixed(0) + "</p>";
        },
      },
      {
        show: filedShowOff("seqNo"),
        label: "工序",
        prop: "seqNo",
        align: "center",
        operator: false,
        // sortable: true,
        // "sort-method": scoreOrder,
        operatorPlaceholder: "精确搜索",
      },
      {
        show: filedShowOff("proName"),
        label: "工序名",
        prop: "proName",
        align: "center",
        width: 110,
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(ProcessSearch),
      },
      {
        show: filedShowOff("mtype"),
        label: "机器型号",
        prop: "mtype",
        align: "center",
        width: 110,
        operatorPlaceholder: "精确搜索",
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(MtTypeSearch),
      },
      {
        show: filedShowOff("reqDate"),
        label: "工序交期",
        prop: "reqDate",
        align: "center",
        width: 120,
        operator: false,
      },
      // {
      //   show: filedShowOff("onlineStatus"),
      //   label: "在线状态",
      //   prop: "onlineStatus",
      //   align: "center",
      //   render: "customRender",
      //   customRender: markRaw(Tag),
      //   comSearchRender: "customRender",
      //   comSearchCustomRender: markRaw(TagSearch),
      // },
      {
        show: filedShowOff("lastproQty"),
        label: "上道工序库存",
        prop: "lastproQty",
        align: "center",
        operator: false,
        width: 120,
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          return "<p>" + (value - 0).toFixed(0) + "</p>";
        },
      },
      {
        show: filedShowOff("requests"),
        label: "工序欠量",
        prop: "requests",
        align: "center",
        width: 120,
        operator: false,
      },
      {
        show: filedShowOff("proQty"),
        label: "当前工序库存",
        prop: "proQty",
        align: "center",
        operator: false,
        width: 120,
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          return "<p>" + (value - 0).toFixed(0) + "</p>";
        },
      },
      {
        show: filedShowOff("toOutQty"),
        label: "委外在途",
        prop: "toOutQty",
        align: "center",
        operator: false,
        width: 110,
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          if (value !== "-") {
            return "<p>" + (value - 0).toFixed(0) + "</p>";
          }
          return "<p>" + value + "</p>";
        },
      },
      {
        show: filedShowOff("hourProQty"),
        label: "小时产能",
        prop: "hourProQty",
        align: "center",
        operator: false,
        width: 110,
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          return "<p>" + (value - 0).toFixed(0) + "</p>";
        },
      },
      {
        show: filedShowOff("allRequests"),
        label: "总需求",
        prop: "allRequests",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("stocks"),
        label: "总库存",
        prop: "stocks",
        align: "center",
        operator: false,
        width: 120,
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          return "<p>" + (value - 0).toFixed(0) + "</p>";
        },
      },
      {
        show: filedShowOff("seqs"),
        label: "工序数",
        prop: "seqs",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("seqDays"),
        label: "工序提前期",
        prop: "seqDays",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("stockFull"),
        label: "库存是否充足",
        prop: "stockFull",
        align: "center",
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(TagSearch),
      },
      {
        show: operatorShowOff([route.path + "/edit", route.path + "/remove"]),
        label: "操作",
        align: "center",
        width: "130",
        render: "buttons",
        fixed: "right",
        operator: false,
        buttons: [
          {
            render: "tipButton",
            name: "info",
            title: "问题跟踪",
            text: "",
            type: "primary",
            icon: "el-icon-ChatLineSquare",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "tipButton",
            name: "more",
            title: "料号详情",
            text: "",
            type: "primary",
            icon: "iconfont icon-chaxunyujisuan",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          // {
          //   render: "confirmButton",
          //   name: "remove",
          //   title: "删除",
          //   text: "",
          //   type: "danger",
          //   icon: "el-icon-DeleteFilled",
          //   class: "table-row-delete",
          //   popconfirm: {
          //     confirmButtonText: "删除",
          //     cancelButtonText: "取消",
          //     confirmButtonType: "danger",
          //     title: "确定删除所选项吗",
          //   },
          //   disabledTip: false,
          //   // 按钮是否显示，请返回布尔值
          //   display: (row: TableRow, field: TableColumn) => {
          //     return true;
          //   },
          //   // 按钮是否禁用，请返回布尔值
          //   disabled: (row: TableRow, field: TableColumn) => {
          //     return false;
          //   },
          //   attr: {},
          // },
        ],
      },
    ],
    filter: {
      pageSize: pageSizeKeep(),
      stockFull: "NO",
    },
    showComSearch: true, //展开通用搜索
    extend: {
      column: true, //是否合并行
      columnFiled: ["goodsNo", "goodReqDate", "cRequests"], //该字段相同合并,优先级最高放前面
      columnMasteFiled: "goodsNo", //合并优先级最高字段
    },
  },
  {
    // 默认表单数据(添加)
    // defaultItems: {
    //   siteOrder: 1,
    //   siteType: 0, //0为地区类型
    // },
  },
  {
    onSubmit: ({
      formEl,
      operate,
      items,
    }: {
      formEl: FormInstance | undefined;
      operate: string;
      items: anyObj;
    }) => {
      console.log("表单提交前", formEl, operate, items);
      return true;
    },
  },
  {
    getList: ({ res }: { res: any }) => {
      //自定义排序逻辑 工序正序确定
      console.log("tableRef.value", res);
      scoreOrderBySelf(res.rows);
      return true;
    }, // 查看后
  }
);

//打开晨会问题跟踪表单
const infoButtonClick = (name: string, row: any) => {
  if (!row) return;
  // 数据来自表格数据,未重新请求api,深克隆,不然可能会影响表格
  let rowClone = _.cloneDeep(row);
  console.log("打开晨会问题跟踪表单row", row);
  baTable.form.extend!["problem"] = rowClone;
  baTable.form.operate = "problem";
};
//打开料号详情页表单
const moreButtonClick = (name: string, row: any) => {
  if (!row) return;
  // 数据来自表格数据,未重新请求api,深克隆,不然可能会影响表格
  followProlem.single = row;
  router.push({ path: "/admin/BoardProcessPull/detail" });
};

onMounted(() => {
  baTable.table.ref = tableRef.value;
  baTable.mount();
  baTable.getList(BoardProcessPull);

  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow }) => {
      if (!baTable.activate) return;
      //回滚功能暂无
      if (data.name == "rollback") {
        // onRollback([data.row[baTable.table.pk!]])
      } else if (data.name == "info") {
        //携带主键字段pk
        infoButtonClick(
          (data.row as TableRow)[baTable.table.pk!],
          data.row as any
        );
      } else if (data.name == "more") {
        //携带主键字段pk
        moreButtonClick(
          (data.row as TableRow)[baTable.table.pk!],
          data.row as any
        );
      }
    }
  );
});

// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("dictionary", dictionary);
provide("dictOperation", dictOperation);
provide("processPull", processPull);
provide("followProlem", followProlem);
provide("dept", dept);
provide("user", user);
provide("router", router);
provide("goods", goods);
</script>
<style lang="scss" scoped>
.el-main {
  padding: 0;
}
.default-main {
  margin: var(--ba-main-space) var(--ba-main-space) 60px var(--ba-main-space);
}
</style>
